<template>
  <div id="swatchSchemeManage">
    <el-card class="box-card" style="margin:15px">
      <div style="margin-bottom:10px">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="clickAdd">新增</el-button>
        <el-button size="small" @click="getList()">刷新</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;padding:5px;"
        :header-cell-style="{
          background: '#333333',
          color: '#ffffff',
          textAlign: 'center'
        }"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" prop="swatchName" label="方案名称" />
        <el-table-column align="center" prop="swatchNum" label="实验板数" />
        <el-table-column align="center" prop="experimentCode.data" label="实验项目" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="clickEdit(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="clickDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增 -->
    <el-dialog :visible.sync="addShow" width="80%" center custom-class="print-dialog">
      <span
        slot="title"
        class="dialog-title"
        style="font-size: 18px;font-weight: 400;color: #FFFFFF;"
      >布板管理</span>
      <div class="edit-dialog">
        <el-form
          ref="basicForm"
          :inline="true"
          :rules="formDataRules"
          :model="formData"
          class="demo-form-inline"
          label-width="100px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="布板方向:" prop="direction.key">
                <el-radio-group v-model="formData.direction.key">
                  <el-radio
                    v-for="(item, key, index) in dicts.DIRECTION"
                    :key="item"
                    :label="key"
                  >{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="方案名称:" prop="swatchName">
                <el-input size="mini" v-model="formData.swatchName" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="板数量:" prop="swatchNum">
                <el-input size="mini" v-model.number="formData.swatchNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="布板行数:" prop="rowNum">
                <el-input size="mini" v-model.number="formData.rowNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="布板列数:" prop="colNum">
                <el-input size="mini" v-model.number="formData.colNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="实验项目:" prop="experimentCode.key">
                <el-radio-group v-model="formData.experimentCode.key">
                  <el-radio
                    v-for="(item, key, index) in dicts.EXPERIMENT_CODE"
                    :key="item"
                    :label="key"
                  >{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="banShow">
              <ban
                @chanageDataList="chanageAddDataList"
                ref="ban"
                v-loading="banAddLoading"
                :banTotal="banTotal"
                :columnList="colNum"
                :direction="formData.direction"
                :rowList="rowNum"
              ></ban>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          style="padding: 6px 19px;"
          @click="onSubmit('set')"
        >设置</el-button>
        <el-button
          size="small"
          type="primary"
          style="padding: 6px 19px;"
          @click="onSubmit('save')"
        >保存</el-button>
      </span>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :visible.sync="editShow" width="80%" center custom-class="print-dialog">
      <span
        slot="title"
        class="dialog-title"
        style="font-size: 18px;font-weight: 400;color: #FFFFFF;"
      >修改</span>
      <div class="edit-dialog">
        <el-form
          ref="basicForm"
          :inline="true"
          :rules="formDataRules"
          :model="editItem"
          class="demo-form-inline"
          label-width="100px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="布板方向:" prop="direction.key">
                <el-radio-group v-model="editItem.direction.key">
                  <el-radio
                    v-for="(item, key, index) in dicts.DIRECTION"
                    :key="item"
                    :label="key"
                  >{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="方案名称:" prop="swatchName">
                <el-input size="mini" v-model="editItem.swatchName" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="板数量:" prop="swatchNum">
                <el-input size="mini" v-model.number="editItem.swatchNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="布板行数:" prop="rowNum">
                <el-input size="mini" v-model.number="editItem.rowNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="布板列数:" prop="colNum">
                <el-input size="mini" v-model.number="editItem.colNum" placeholder="输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="实验项目:" prop="experimentCode.key">
                <el-radio-group v-model="editItem.experimentCode.key">
                  <el-radio
                    v-for="(item, key, index) in dicts.EXPERIMENT_CODE"
                    :key="item"
                    :label="key"
                  >{{ item }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="banEditShow">
              <banEdit
                v-loading="banEditLoading"
                @chanageDataList="chanageEditDataList"
                ref="banEdit"
                :banTotal="banTotal"
                :columnList="columnList"
                :rowList="rowList"
                :direction="editItem.direction"
                :dataList="editItem.swatchModel"
              ></banEdit>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          style="padding: 6px 19px;"
          @click="onSubmit('editSet')"
        >设置</el-button>
        <el-button
          size="small"
          type="primary"
          style="padding: 6px 19px;"
          @click="onSubmit('editSave')"
        >保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QualityManageApi from "@/api/QualityManage.js";
import { initDicts } from "@/utils/commons";
import ban from "@/components/ban/ban";
import banEdit from "@/components/ban/banEdit";

export default {
  components: {
    ban,
    banEdit
  },
  data() {
    return {
      dicts: {
        EXPERIMENT_CODE: {},
        DIRECTION: {}
      },
      // 转菊花
      loading: false,
      // 新增弹窗
      addShow: false,
      // 是否显示板
      banShow: false,
      // 是否显示板
      banEditShow: false,
      // 修改布板
      editShow: false,
      // 板数量
      banTotal: 1,
      // 表格数据
      tableData: [],
      // 修改数据
      editItem: {
        direction: {
          data: "",
          key: ""
        },
        experimentCode: {
          key: "",
          data: ""
        }
      },
      // 添加数据
      formData: {
        direction: {
          data: "",
          key: ""
        },
        experimentCode: {
          data: "",
          key: ""
        },
        swatchModel: "",
        swatchName: "",
        swatchNum: 1,
        rowNum: 8,
        colNum: 12
      },
      formDataRules: {
        swatchName: [{ required: true, message: "   ", trigger: "change" }],
        swatchNum: [
          { required: true, message: "请输入板数量", trigger: "change" }
        ],
        rowNum: [
          { required: true, message: "请输入布板行数", trigger: "change" }
        ],
        colNum: [
          { required: true, message: "请输入布板列数", trigger: "change" }
        ],
        "experimentCode.key": [
          { required: true, message: "请选择项目", trigger: "change" }
        ],
        "direction.key": [
          { required: true, message: "请选择布板方向", trigger: "change" }
        ]
      },
      // 布板列数
      rowList: [],
      // 布板行数
      columnList: [],
      banEditLoading: false, //修改版转菊花
      banAddLoading: false, //修改版转菊花
      // 布板所需数据
      //列
      rowNum: [],
      //行
      colNum: []
    };
  },
  mounted() {
    // 获取字典
    initDicts(["EXPERIMENT_CODE", "DIRECTION"], this.dicts);

    this.getList();
  },
  methods: {
    // 过滤去重(获取布板列数)
    filRowList(arr) {
      let data = [];
      arr.forEach(item => {
        data.push(item.col);
      });
      return Array.from(new Set(data));
    },
    // 过滤去重(获取布板列数)
    filColumnList(arr) {
      let data = [];
      arr.forEach(item => {
        data.push(
          this.editItem.direction.key == "horizontal"
            ? item.r
            : item.pos.split("-")[1]
        );
      });
      return Array.from(new Set(data));
    },
    // 初始化布板
    initBan(num) {
      var column = [];
      var row = this.columnList;
      var result = [];

      if (this.editItem.direction.key == "horizontal") {
        column = this.rowList;
        for (let banIndex = 0; banIndex < num; banIndex++) {
          for (const columnIndex in column) {
            for (const rowIndex in row) {
              if (row[rowIndex].type == "") {
                let item = {
                  ban: banIndex + 1,
                  r: row[rowIndex].id,
                  col: column[columnIndex],
                  pos: [
                    banIndex + 1,
                    column[columnIndex],
                    row[rowIndex].id < 10
                      ? "0" + row[rowIndex].id
                      : row[rowIndex].id
                  ].join("-"),
                  key: "",
                  s: "",
                  m: "",
                  exist: "N"
                };
                result.push(item);
              }
            }
          }
        }
      } else {
        //定义基本参数
        this.$rowData.forEach((item, index) => {
          if (index < row.length - 1) {
            column[index] = item;
          }
        });
        for (let banIndex = 0; banIndex < num; banIndex++) {
          for (const columnIndex in column) {
            for (const rowIndex in row) {
              if (row[rowIndex].type == "") {
                if (columnIndex < this.rowList.length) {
                  let item = {
                    ban: banIndex + 1,
                    r: Number(columnIndex) + 1,
                    col: row[Number(columnIndex) + 1].id,
                    pos: [
                      banIndex + 1,
                      column[rowIndex - 1],
                      Number(columnIndex) + 1 < 10
                        ? 0 + Number(columnIndex) + 1
                        : Number(columnIndex) + 1
                    ].join("-"),
                    key: "",
                    s: "",
                    m: "",
                    exist: "N"
                  };
                  result.push(item);
                }
              }
            }
          }
        }
      }

      result.map((item, index) => {
        item.key = index + 1;
      });
      return result;
    },
    // 点击新增
    clickAdd() {
      this.addShow = true;
      this.banShow = false;
      setTimeout(() => {
        this.$refs["basicForm"].resetFields();
      }, 50);
    },
    // 修改
    clickEdit(v) {
      this.editShow = true;
      this.banEditLoading = true;
      this.editItem = v;
      this.columnList = [];
      this.rowList = [];
      this.banTotal = v.swatchNum;
      QualityManageApi.swatchSchemeManage.getById(v.id).then(res => {
        this.editItem.swatchModel = res.data.data.swatchModel;

        this.filColumnList(this.editItem.swatchModel).forEach((item, index) => {
          this.columnList[index] = {
            id:
              this.editItem.direction.key == "horizontal"
                ? item
                : this.$rowData[index],
            type: ""
          };
        });
        if (this.columnList[0].type != "banIndex") {
          this.columnList.unshift({ id: "1", type: "banIndex" });
        }
        this.rowList = this.filRowList(this.editItem.swatchModel); //根据布板数组过滤行数
        this.banEditShow = true;

        setTimeout(() => {
          this.$refs.banEdit.getList();
          this.banEditLoading = false;
        }, 200);
      });
    },
    // 删除
    clickDelete(v) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        QualityManageApi.swatchSchemeManage
          .delete({ "ids[]": v.id })
          .then(res => {
            if (res.status == "200") {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            } else {
              this.$message.error(res.statusText);
            }
          });
      });
    },
    // 添加设置表格
    chanageAddDataList(v) {
      this.formData.swatchModel = v;
    },
    // 修改设置表格
    chanageEditDataList(v) {
      this.editItem.swatchModel = v;
    },
    // 按钮
    onSubmit(type) {
      if (type == "save") {
        this.$refs["basicForm"].validate(valid => {
          if (valid) {
            QualityManageApi.swatchSchemeManage.add(this.formData).then(res => {
              if (res.status === 200) {
                this.$message({
                  type: "success",
                  message: "保存成功!"
                });
                this.addShow = false;
                this.getList();
              } else {
                this.$message.error("保存失败!");
              }
            });
          } else {
            return false;
          }
        });
      } else if (type == "set") {
        this.$refs["basicForm"].validate(valid => {
          if (valid) {
            this.banAddLoading = true;
            this.banTotal = this.formData.swatchNum;
            this.rowNum = [];
            this.colNum = [];
            // 行数
            for (
              let rowIndex = "0";
              rowIndex < this.formData.rowNum;
              rowIndex++
            ) {
              this.rowNum.push(this.$rowData[rowIndex]);
            }
            // 列数
            for (
              let colIndex = "1";
              colIndex < this.formData.colNum + 1;
              colIndex++
            ) {
              this.colNum.push({
                id:
                  this.formData.direction.key == "horizontal"
                    ? colIndex.toString()
                    : this.$rowData[colIndex - 1],
                type: ""
              });
            }
            this.colNum.unshift({ id: "1", type: "banIndex" });
            this.banShow = true;
            setTimeout(() => {
              this.$refs.ban.getDataList();
              this.$refs.ban.getList();
              this.banAddLoading = false;
            }, 200);
          } else {
            return false;
          }
        });
      } else if (type == "editSet") {
        this.$refs["basicForm"].validate(valid => {
          if (valid) {
            this.banTotal = this.editItem.swatchNum;
            this.editItem.swatchModel = [];
            this.banEditLoading = true;

            this.rowNum = [];
            this.colNum = [];
            // 行数
            for (
              let rowIndex = "0";
              rowIndex < this.editItem.rowNum;
              rowIndex++
            ) {
              this.rowNum.push(this.$rowData[rowIndex]);
            }
            // 列数
            for (
              let colIndex = "1";
              colIndex < this.editItem.colNum + 1;
              colIndex++
            ) {
              this.colNum.push({
                id:
                  this.editItem.direction.key == "horizontal"
                    ? colIndex.toString()
                    : this.$rowData[colIndex - 1],
                type: ""
              });
            }

            this.colNum.unshift({ id: "1", type: "banIndex" });
            this.rowList = this.rowNum;
            this.columnList = this.colNum;
            this.editItem.swatchModel = this.initBan(this.banTotal);

            setTimeout(() => {
              this.$refs.banEdit.getList();
              this.banEditLoading = false;
            }, 200);
          } else {
            return false;
          }
        });
      } else if (type == "editSave") {
        this.banEditShow = true;
        this.$refs["basicForm"].validate(valid => {
          if (valid) {
            QualityManageApi.swatchSchemeManage
              .edit(this.editItem)
              .then(res => {
                if (res.status === 200) {
                  this.$message({
                    type: "success",
                    message: "保存成功!"
                  });
                  this.editShow = false;
                  this.getList();
                } else {
                  this.$message.error("保存失败!");
                }
              });
          } else {
            return false;
          }
        });
      }
    },
    // 获取数据
    getList() {
      this.loading = true;
      let data = {
        current: 1,
        map: {},
        model: {
          experimentCode: {
            data: "",
            key: ""
          },
          swatchName: ""
        },
        order: "descending",
        size: 10,
        sort: "id"
      };
      QualityManageApi.swatchSchemeManage.page(data).then(res => {
        this.tableData = res.data.data.records;
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="less">
.flex {
  display: flex;
  align-items: center;
  justify-content: center;
}
#swatchSchemeManage {
  #bottom-form,
  #top-form {
    .el-form-item__content {
      width: 90%;
    }
  }
}
</style>
